<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace App\AiPro\Mapper;

use App\AiPro\Model\AiproCategory;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 导航页分类Mapper类
 */
class AiproCategoryMapper extends AbstractMapper
{
    /**
     * @var AiproCategory
     */
    public $model;

    public function assignModel()
    {
        $this->model = AiproCategory::class;
    }

    /**
     * 获取前端选择树
     * @return array
     */
    public function getSelectTree(): array
    {
        return $this->model::query()
            ->select(['id', 'pid', 'id AS value', 'title AS label'])
            ->get()->toTree();
    }


    /**
     * 查询树名称
     * @param array|null $ids
     * @return array
     */
    public function getTreeName(array $ids = null): array
    {
        return $this->model::withTrashed()->whereIn('id', $ids)->pluck('title')->toArray();
    }

    /**
     * @param int $id
     * @return bool
     */
    public function checkChildrenExists(int $id): bool
    {
        return $this->model::withTrashed()->where('pid', $id)->exists();
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        
        // 
        if (!empty($params['id'])) {
            $query->where('id', '=', $params['id']);
        }

        // 标题
        if (!empty($params['title'])) {
            $query->where('title', 'like', '%'.$params['title'].'%');
        }

        // pid
        if (!empty($params['pid'])) {
            $query->where('pid', '=', $params['pid']);
        }

        // 简介
        if (!empty($params['desc'])) {
            $query->where('desc', 'like', '%'.$params['desc'].'%');
        }

        // 状态
        if (!empty($params['status'])) {
            $query->where('status', '=', $params['status']);
        }

        // 
        if (!empty($params['created_at']) && is_array($params['created_at']) && count($params['created_at']) == 2) {
            $query->whereBetween(
                'created_at',
                [ $params['created_at'][0], $params['created_at'][1] ]
            );
        }

        return $query;
    }
}